package com.qkl.xiatang.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.feed.ZooWeighOutDTO;
import com.qkl.xiatang.app.dto.print.PrintResponseDTO;
import com.qkl.xiatang.app.entity.PrinterEntity;
import com.qkl.xiatang.app.entity.feed.FeedAllocDetailEntity;
import com.qkl.xiatang.app.entity.feed.FeedAllocQtyEntity;
import com.qkl.xiatang.app.entity.feed.FeedEntity;
import com.qkl.xiatang.app.entity.pond.PondEntity;
import com.qkl.xiatang.app.utils.AppSessionUtils;
import com.qkl.xiatang.app.utils.HttpResponse;
import com.qkl.xiatang.app.utils.HttpUtils;
import com.qkl.xiatang.app.utils.SHAUtils;
import com.qkl.xiatang.app.mapper.FeedAllocQtyMapper;
import com.qkl.xiatang.app.mapper.FeedManagerMapper;
import com.qkl.xiatang.app.mapper.PondManagerMapper;
import com.qkl.xiatang.app.mapper.PrinterMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class PrintService {

    private static final String URL = "https://api.feieyun.cn/Api/Open/";

    @Autowired
    private ConfigService configService;

    @Autowired
    private PondManagerMapper pondManagerMapper;

    @Autowired
    private FeedManagerMapper feedManagerMapper;

    @Autowired
    private FeedAllocQtyMapper feedAllocQtyMapper;

    @Autowired
    private PrinterMapper printerMapper;

    @Autowired
    private AppThreadPoolService appThreadPool;

    /**
     * 网络打印
     * @param content
     * @return
     */
    public BusinessDTO<PrintResponseDTO> printMsg(String user,String ukey,String sn,String content){
        String stime = SHAUtils.printStime();
        if(StringUtils.isEmpty(user)){
            user = "404004086@qq.com";
        }
        if(StringUtils.isEmpty(user)){
            ukey = "CmrM6j8T9TXzLpEt";
        }

        Map<String,String> params = new HashMap<>();
        params.put("user",user);
        params.put("stime",stime);
        params.put("sig",SHAUtils.printSign(user,ukey,stime));
        params.put("apiname","Open_printMsg");
        params.put("sn",sn);
        params.put("content",content);
        params.put("times","1");
        log.info("=====printMsg params={}",params);
        HttpResponse<String> response  = HttpUtils.postRequestForm(URL,params);
        if(response.isSuccess()){
            PrintResponseDTO printResponseDTO = JSON.parseObject(response.getData(),PrintResponseDTO.class);
            if(printResponseDTO.success()){
                return BusinessDTO.sucessBusiness(printResponseDTO,"网络打印成功");
            }else {
                return BusinessDTO.failBusiness("网络打印失败:" + printResponseDTO.getMsg());
            }
        }
        return BusinessDTO.failBusiness("网络打印失败:" + response.getMsg());
    }

    /**
     * 打印动保称料
     * @param pondId
     * @param weighUserName
     * @param feedId
     * @param weigh
     * @return
     */
    public void printWeighZoo(String pondId,String weighUserName,String feedId,Double weigh){
        String companyId = AppSessionUtils.getCompanyId();
        appThreadPool.execute(()->{
            BusinessDTO<PrintResponseDTO>  businessDTO =printWeighZoo0(pondId,weighUserName,feedId,weigh,companyId);
            log.info("====async print printWeighZoo.businessDTO={}",businessDTO);
        });
    }

    /**
     * 打印动保称料,列表
     * @param weighUserName
     * @param zooWeighList
     */
    public void printWeighZooList(String weighUserName, List<ZooWeighOutDTO> zooWeighList){
        String companyId = AppSessionUtils.getCompanyId();
        appThreadPool.execute(()->{
            printWeighZooList0(weighUserName,companyId,zooWeighList);
        });
    }

    public void printWeighZooList0(String weighUserName,String companyId , List<ZooWeighOutDTO> zooWeighList){
        PrinterEntity printer = this.queryPrinter(companyId, 2);
        for(ZooWeighOutDTO zooWeigh : zooWeighList){
            this.printWeighZoo1(zooWeigh.getPondName(),weighUserName,zooWeigh.getFeedName(),zooWeigh.getQty(),printer);
        }
    }

    private BusinessDTO<PrintResponseDTO> printWeighZoo0(String pondId,String weighUserName,String feedId,Double weigh,String companyId){
        PrinterEntity printer = this.queryPrinter(companyId, 2);
        String pondName = this.getPondName(pondId);
        String feedName = this.getFeedName(feedId);
        return this.printWeighZoo1(pondName,weighUserName,feedName,weigh,printer);
    }
    private BusinessDTO<PrintResponseDTO> printWeighZoo1(String pondName,String weighUserName,String feedName,Double weigh,PrinterEntity printer){
        if(null == weigh || weigh == 0.0){
            return BusinessDTO.failBusiness("无重量无需打印");
        }
        StringBuffer sb = new StringBuffer();
        sb.append("<CB>动保").append(" ").append(pondName).append("塘</CB><BR>");
        sb.append("打印时间:").append(printTime()).append("<BR>");
        sb.append("称重员:").append(weighUserName).append("<BR>");
        sb.append("<B>").append("动保名称：").append(feedName).append("</B><BR>");
        sb.append("<B>").append("重量：").append(weigh).append("</B><BR>");

        String content = sb.toString();
        log.info("===== printWeighZoo.content={}",content);
        if( null == printer ){
            log.info("====async print printWeighZoo. not print={}","未配置打印机");
            return BusinessDTO.failBusiness("未配置打印机");
        }
        String user = printer.getUser();
        String ukey = printer.getUkey();
        String sn = printer.getPrinterSn();
        BusinessDTO<PrintResponseDTO> respone = this.printMsg(user,ukey,sn,content);
        log.info("=============== printWeighZoo respone={}",respone);
        return respone;
    }

    public void printWeighFeed(List<FeedAllocDetailEntity> detailEntityList){
        if(ObjectUtils.isEmpty(detailEntityList)){
            return;
        }
        String companyId = AppSessionUtils.getCompanyId();
        appThreadPool.execute(()->{
            for (FeedAllocDetailEntity detailEntity : detailEntityList) {
                BusinessDTO<PrintResponseDTO> businessDTO = printWeighFeed0(detailEntity, companyId);
                log.info("====async print printWeighFeed.businessDTO={}", businessDTO);
            }
        });
    }

    /**
     * 打印饲料称料
     * @param detailEntity
     */
    public void printWeighFeed(FeedAllocDetailEntity detailEntity){
        String companyId = AppSessionUtils.getCompanyId();
        appThreadPool.execute(()->{
            BusinessDTO<PrintResponseDTO> businessDTO = printWeighFeed0(detailEntity,companyId);
            log.info("====async print printWeighFeed.businessDTO={}",businessDTO);
        });
    }

    private BusinessDTO<PrintResponseDTO> printWeighFeed0(FeedAllocDetailEntity detailEntity,String companyId ){
        //String weighName = "饲料";
        List<FeedAllocQtyEntity> qtyList = feedAllocQtyMapper.selectList(new QueryWrapper<FeedAllocQtyEntity>().eq("detail_id",detailEntity.getId()));
        if(ObjectUtils.isEmpty(qtyList)){
            return BusinessDTO.failBusiness("饲料数据异常");
        }
        String pondName = this.getPondName(detailEntity.getPondId());
        StringBuffer sb = new StringBuffer();
        sb.append("<CB>饲料").append(" ").append(detailEntity.getName()).append(" ").append(pondName).append("塘</CB><BR>");
        sb.append("打印时间:").append(printTime()).append("<BR>");
        sb.append("称重员:").append(detailEntity.getWeighUserName()).append("<BR>");

        //String printTemp = configService.getPrintTemplate();
        //String printFeedTemp = configService.getPrintFeedTemplate();
        //String content = String.format(printTemp,weighName,printTime(),pondName,detailEntity.getWeighUserName());
        for(FeedAllocQtyEntity qtyEntity : qtyList){
            Double weigh = qtyEntity.getQty();
            if(null == weigh || weigh == 0.0){
                continue;
            }
            String feedName = this.getFeedName(qtyEntity.getFeedId());
            sb.append("<B>").append("饲料名称：").append(feedName).append("</B><BR>");
            sb.append("<B>").append("重量：").append(weigh).append("</B><BR>");
        }
        String content = sb.toString();
        log.info("===== printWeighFeed.content={}",content);
        PrinterEntity printer = this.queryPrinter(companyId,1);
        if( null == printer ){
            return BusinessDTO.failBusiness("未配置打印机");
        }
        String user = printer.getUser();
        String ukey = printer.getUkey();
        String sn = printer.getPrinterSn();
        BusinessDTO<PrintResponseDTO> respone = this.printMsg(user,ukey,sn,content);
        log.info("=============== printWeighFeed respone={}",respone);
        return respone;
    }

    private String getFeedName(String feedId){
        String feedName = "";
        FeedEntity feedEntity = feedManagerMapper.selectById(feedId);
        if(null != feedEntity){
            feedName = feedEntity.getName();
        }
        return feedName;
    }

    private String getPondName(String pondId){
        String pondName = "";
        PondEntity pond = pondManagerMapper.selectById(pondId);
        if(null != pond ){
            pondName = pond.getName();
        }
        return pondName;
    }

    private static  String printTime(){
        return new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date());
    }

    private PrinterEntity queryPrinter(String companyId,Integer type){
        List<PrinterEntity>  printerList = printerMapper.selectList(new QueryWrapper<PrinterEntity>().eq("company_id",companyId));
        if(ObjectUtils.isEmpty(printerList)){
            return null;
        }
        PrinterEntity printer = null;
        for(PrinterEntity entity : printerList){
            if( null != entity.getType() && entity.getType().contains(String.valueOf(type))){
                log.info("==========queryPrinter no={},type={},intype={}",entity.getPrinterSn(),entity.getType(),type);
                printer = entity;
                break;
            }
        }
        return printer;
    }

}
